import React, { Component } from 'react'
import { connect } from 'react-redux'
import $http from '../http';
export class Login extends Component {

  state={
    username:'',
    password:''
  }

  constructor(props){
    super(props);
    this.handleUsernameChange=this.handleUsernameChange.bind(this);
    this.handlePasswordChange=this.handlePasswordChange.bind(this);
    this.login=this.login.bind(this);
  }

  handleUsernameChange(e){
   this.setState({
     username:e.target.value
   })
  }

  handlePasswordChange(e){
    this.setState({
      password:e.target.value
    })
  }

  login(){
   this.props.login({username:this.state.username,password:this.state.password}).then(
     (res)=>{
       alert(res);
       this.props.history.push('/list');
      }

     ).catch((err)=>{alert(err)});
  }

  render() {
    return (
      <div>
      Login

     <input name="username" onChange={
       this.handleUsernameChange
     } />
     <input name="password" onChange={this.handlePasswordChange} />
     <button onClick={this.login}>登录</button>
    </div>
    )
  }
}

const mapStateToProps = (state) => ({
  ...state
})

const mapDispatchToProps = (dispatch)=>{
    return {
      login(user){
      return  $http.post('/api/login',user).then((res)=>{
          console.log('login res',res);
          if(res.code===0){
         
            dispatch({type:'SET_TOKEN',data:res.token});
          return   Promise.resolve(res.message);

          }else{
          return  Promise.reject(res.message)
          }
        }).catch((err)=>Promise.reject(err))
      }
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(Login)
